﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Problem21
{
    class Program
    {
        static void Main(string[] args)
        {
            //ExtractDofN(16);
            Dictionary<int, int> dofn = new Dictionary<int, int>(10000);
            long sum = 0;

            for (int n = 1; n < 10000; n++)
            {
                int sumofd = ExtractDofN(n);

                dofn.Add(n, sumofd);

                if (sumofd >= 10000 && dofn.ContainsKey(sumofd) == false)
                {
                    dofn.Add(sumofd, ExtractDofN(sumofd));
                }
            }

            foreach (var n in dofn)
            {
                int a = n.Key;
                int b = n.Value;

                if (a < 10000 && a > 0 && b > 0)
                {
                    if (dofn[b] == a && a != b)
                    {
                        sum += a;
                    }
                }
            }

            Console.WriteLine(sum);
            Console.ReadKey();
        }

        private static int ExtractDofN(int n)
        {
            HashSet<int> d = new HashSet<int>();

            for (int divisor = (int)Math.Ceiling(Math.Sqrt(n)); divisor > 0; divisor--)
            {
                if (divisor < n && n % divisor == 0)
                {
                    d.Add(divisor);
                    var other = n / divisor;

                    if (other < n)
                    {
                        d.Add(other);
                    }
                }
            }

            int sumofd = d.Sum();
            return sumofd;
        }
    }
}
